package com.huhao.smark;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;

import android.animation.ObjectAnimator;
import android.content.SharedPreferences;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private Button homeButton, ledgerButton, personalButton, settingsButton;
    private ViewPager2 viewPager2;
    private SharedPreferences sharedPreferences;
    private SharedPreferences.OnSharedPreferenceChangeListener preferenceChangeListener;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        homeButton = findViewById(R.id.home_button);
        ledgerButton = findViewById(R.id.ledger_button);
        personalButton = findViewById(R.id.personal_button);
        settingsButton = findViewById(R.id.settings_button);
        viewPager2 = findViewById(R.id.view_pager2);

        setupNavigation();
        setupViewPager();
        setupSharedPreferencesListener();

        if (getIntent().hasExtra("SHOW_PAGE")) {
            int showPage = getIntent().getIntExtra("SHOW_PAGE", 0);
            viewPager2.setCurrentItem(showPage);
        } else {
            // 默认初始化为首页
            setCurrentPage(homeButton);
        }
        // 检查登录状态并更新界面
        updateUIBasedOnLoginStatus();
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 开始监听 SharedPreferences 的变化
        sharedPreferences.registerOnSharedPreferenceChangeListener(preferenceChangeListener);
        updateUIBasedOnLoginStatus();
    }

    @Override
    protected void onPause() {
        super.onPause();
        // 停止监听 SharedPreferences 的变化
        sharedPreferences.unregisterOnSharedPreferenceChangeListener(preferenceChangeListener);
    }

    private void setupSharedPreferencesListener() {
        sharedPreferences = getSharedPreferences("app_prefs", MODE_PRIVATE);
        preferenceChangeListener = new SharedPreferences.OnSharedPreferenceChangeListener() {
            @Override
            public void onSharedPreferenceChanged(SharedPreferences sp, String key) {
                if (key.equals("isLoggedIn")) {
                    updateUIBasedOnLoginStatus();
                }
                // 如果有其他需要监听的键值，可以在这里添加分支
            }
        };
    }

    private void setupNavigation() {
        homeButton.setOnClickListener(v -> {
            setCurrentPage(homeButton);
            viewPager2.setCurrentItem(0);
        });

        ledgerButton.setOnClickListener(v -> {
            setCurrentPage(ledgerButton);
            viewPager2.setCurrentItem(1);
        });

        personalButton.setOnClickListener(v -> {
            setCurrentPage(personalButton);
            viewPager2.setCurrentItem(2);
        });

        settingsButton.setOnClickListener(v -> {
            setCurrentPage(settingsButton);
            viewPager2.setCurrentItem(3);
        });

        // 初始化为首页
        setCurrentPage(homeButton);
    }

    private void setupViewPager() {
        ViewPagerAdapter adapter = new ViewPagerAdapter(this);
        adapter.addFragment(new HomeFragment());
        adapter.addFragment(new LedgerFragment());
        adapter.addFragment(new PersonalFragment());
        adapter.addFragment(new SettingsFragment());
        viewPager2.setAdapter(adapter);

        // 注册页面变更回调，以更新按钮状态
        viewPager2.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
                switch (position) {
                    case 0:
                        setCurrentPage(homeButton);
                        break;
                    case 1:
                        setCurrentPage(ledgerButton);
                        break;
                    case 2:
                        setCurrentPage(personalButton);
                        break;
                    case 3:
                        setCurrentPage(settingsButton);
                        break;
                }
            }
        });
    }

    private void setCurrentPage(Button selectedButton) {
        int defaultColor = getResources().getColor(R.color.default_color, getTheme());
        int activeColor = getResources().getColor(R.color.active_color, getTheme());

        Button[] buttons = { homeButton, ledgerButton, personalButton, settingsButton };

        for (Button button : buttons) {
            int currentColor = ((ColorDrawable) button.getBackground()).getColor();
            if (button == selectedButton) {
                animateButtonBackground(button, currentColor, activeColor);
            } else {
                animateButtonBackground(button, currentColor, defaultColor);
            }
        }
    }

    private void updateUIBasedOnLoginStatus() {
        // 从 SharedPreferences 中读取登录状态
        boolean isLoggedIn = sharedPreferences.getBoolean("isLoggedIn", false);

        // 根据登录状态更新界面
        if (isLoggedIn) {
            // 显示或隐藏内容视具体需求而定
            // 例如，更新某些按钮的显示状态
        } else {
            // 显示或隐藏内容视具体需求而定
            // 例如，显示登录界面，隐藏内容区域
        }
    }

    public static class ViewPagerAdapter extends FragmentStateAdapter {
        private final List<Fragment> mFragmentList = new ArrayList<>();

        public ViewPagerAdapter(@NonNull MainActivity fragmentActivity) {
            super(fragmentActivity);
        }

        public void addFragment(Fragment fragment) {
            mFragmentList.add(fragment);
        }

        @NonNull
        @Override
        public Fragment createFragment(int position) {
            return mFragmentList.get(position);
        }

        @Override
        public int getItemCount() {
            return mFragmentList.size();
        }
    }

    private void animateButtonBackground(Button button, int fromColor, int toColor) {
        ObjectAnimator colorAnim = ObjectAnimator.ofArgb(button, "backgroundColor", fromColor, toColor);
        colorAnim.setDuration(300);
        colorAnim.start();
    }

    public void showLedgerPage(int position) {
        Fragment fragment;
        if (position == 0) {
            fragment = new DetailFragment();
        } else {
            fragment = new FinanceFragment();
        }

        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.container, fragment);
        transaction.commit();
    }
}